package eiisan.crypto.demo;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Demo {

    public static void main(String[] args) {
        String screctKey = "123";
        String content = "Hello";
        encrypt(content,screctKey);
    }

    /**
     * 加密
     * @param content
     * @param screctKey
     */
    public static void encrypt(String content,String screctKey){
        MessageDigest md5= null;
        MessageDigest md2= null;

        //内容 + 密钥
        //原因：如果单单只是内容，攻击方也是可以通过MD5得到sign1，拼接攻击方不知到的密钥，在攻击方篡改内容后将得到不同的sign2
        //当然攻击方可以根据sign1解密从而获得密钥
        String src = content + screctKey;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md2 = MessageDigest.getInstance("MD2");
            byte[] digest5 = md5.digest(src.getBytes());
            byte[] digest2 = md2.digest(src.getBytes());
            System.out.println("JDK MD5: "+ Hex.encodeHexString(digest5));
            System.out.println("JDK MD2: "+ Hex.encodeHexString(digest2));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}